package com.flyou.ccnucenter.ui.frgment;

import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.RelativeLayout;

import com.daimajia.slider.library.Animations.DescriptionAnimation;
import com.daimajia.slider.library.SliderLayout;
import com.daimajia.slider.library.SliderTypes.BaseSliderView;
import com.daimajia.slider.library.SliderTypes.TextSliderView;
import com.flyou.ccnucenter.Constant;
import com.flyou.ccnucenter.R;
import com.flyou.ccnucenter.ResideMenu.ResideMenu;
import com.flyou.ccnucenter.adapter.SchoolAdapter;
import com.flyou.ccnucenter.domain.Image;
import com.flyou.ccnucenter.domain.News;
import com.flyou.ccnucenter.ui.activity.MainActivity;
import com.flyou.ccnucenter.ui.activity.NewsDetialActivity;
import com.flyou.ccnucenter.utils.MyLog;
import com.flyou.ccnucenter.utils.OkHttpClientManager;
import com.flyou.ccnucenter.utils.SPUtils;
import com.flyou.ccnucenter.utils.UrlUtils.NewsUrl;
import com.flyou.ccnucenter.utils.UrlUtils.main.NewsUrlPaster;
import com.flyou.ccnucenter.widget.AutoLoadListView;
import com.flyou.ccnucenter.widget.WaveSwipeRefreshLayout.WaveSwipeRefreshLayout;
import com.flyou.ccnucenter.widget.loading.LoadingView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import com.squareup.okhttp.Request;
import com.umeng.analytics.MobclickAgent;

import java.lang.reflect.Type;
import java.util.List;


public class SchoolNewFragment extends Fragment implements AutoLoadListView.LoadMoreListener, WaveSwipeRefreshLayout.OnRefreshListener {
    private int lastPosotion;
    private Button reTry;
    private RelativeLayout failed_view;
    private LoadingView loadingView;
    private SchoolAdapter schoolNewsAdapter;
    private List<News> newsData;
    private Image.ImagesEntity image;
    private View parentView;
    private ResideMenu resideMenu;
    private SliderLayout sliderLayout;
    private AutoLoadListView listView;
    private WaveSwipeRefreshLayout waveSwipeRefreshLayout;
    private int currentPage = 1;
    private boolean isRefresh = true;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        parentView = inflater.inflate(R.layout.home, container, false);
        return parentView;

    }

    private void initDatas() {
//        获取轮播图数据
        String bannerImages = (String) SPUtils.get(getActivity(), "bannerImages", "");
        if (TextUtils.isEmpty(bannerImages)) {
            getViewPagerImageDatas();
        } else {
            Image image = toObj(bannerImages, new TypeToken<Image>() {
            }.getType());
            setBannerADapter(image);
        }

//        轮播图切换方式
        sliderLayout.setPresetTransformer(SliderLayout.Transformer.DepthPage);
//        轮播图下面标志圆点的位置
        sliderLayout.setPresetIndicator(SliderLayout.PresetIndicators.Right_Bottom);
//        切换动画
        sliderLayout.setCustomAnimation(new DescriptionAnimation());
//        切换时间
        sliderLayout.startAutoCycle(0, 4000, true);

    }

    //        获取并设置轮播图数据
    private void getViewPagerImageDatas() {

        OkHttpClientManager.getAsyn(Constant.IMAGE_DESC, new OkHttpClientManager.ResultCallback<Image>() {
            @Override
            public void onError(Request request, Exception e) {
                Log.d("SchoolNewFragment", "error:" + e.toString());
            }

            @Override
            public void onResponse(Image response) {
                String json = toJson(response);
                SPUtils.put(getActivity(), "bannerImages", json);
                setBannerADapter(response);
            }
        });
    }

    public void setBannerADapter(Image response) {
        List<Image.ImagesEntity> images = response.getImages();
        for (int i = 0; i < images.size(); i++) {
            TextSliderView textSliderView = new TextSliderView(getActivity());
            // initialize a SliderLayout
            textSliderView
                    .description(images.get(i).getImageDesc())
                    .image(images.get(i).getImageUrl())
                    .setScaleType(BaseSliderView.ScaleType.Fit)
            ;
            //           增加其他信息
            textSliderView.bundle(new Bundle());
            textSliderView.getBundle()
                    .putString("extra", images.get(i).getImageDesc());

            sliderLayout.addSlider(textSliderView);
        }
    }

    private void setUpViews() {
        MainActivity parentActivity = (MainActivity) getActivity();
        resideMenu = parentActivity.getResideMenu();
        listView = (AutoLoadListView) parentView.findViewById(R.id.listView);

        //将轮播图添加到listview的头部进行显示
        View listview_header_view = View.inflate(getActivity(), R.layout.lisvtview_header_view, null);
        sliderLayout = (SliderLayout) listview_header_view.findViewById(R.id.slider);
        listView.addHeaderView(listview_header_view);
        listView.setLoadMoreListener(this);
        //      防止侧滑菜单与viewpager冲突
        resideMenu.addIgnoredView(listview_header_view);
        //        下拉刷新
        waveSwipeRefreshLayout = (WaveSwipeRefreshLayout) parentActivity.findViewById(R.id.waveRefresh);
        waveSwipeRefreshLayout.setColorSchemeColors(Color.WHITE, Color.WHITE);
        waveSwipeRefreshLayout.setOnRefreshListener(this);
        waveSwipeRefreshLayout.setWaveColor(getResources().getColor(R.color.title_bar));


//        加载动画
        loadingView = (LoadingView) parentActivity.findViewById(R.id.loadingView);

        loadingView.setLoadingText("正在拼命加载数据……");
        loadingView.setVisibility(View.VISIBLE);

//        加载数据错误页面
        reTry = (Button) parentView.findViewById(R.id.reTry);
        reTry.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                refresh();
                loadingView.setVisibility(View.VISIBLE);
            }
        });
        failed_view = (RelativeLayout) parentView.findViewById(R.id.failed_view);


    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setUpViews();
        initDatas();
        //从磁盘获取数据
        getDataFromDisk();
    }

    //下拉刷新操作
    @Override
    public void onRefresh() {
        isRefresh = true;
        refresh();

    }

    @Override
    public void onResume() {


        super.onResume();
        MobclickAgent.onPageStart("学校新闻"); //统计页面
    }

    private void getDataFromDisk() {
        Gson gson = new Gson();
        String jsonString = (String) SPUtils.get(getActivity(), Constant.SCHOOL_NEWS_DATA, "");

        if (TextUtils.isEmpty(jsonString)) {
//            从网络获取数据
            isRefresh = true;
            new getDataFromNet().execute(NewsUrl.getSchoolNewsUrl(1));
            MyLog.d("SchoolNewFragment", "从网络获取数据");
        } else {
            MyLog.d("SchoolNewFragment", "从硬盘获取数据");
            newsData = gson.fromJson(jsonString, new TypeToken<List<News>>() {
            }.getType());
            loadingView.setVisibility(View.GONE);
            setAdapter(newsData);
            isRefresh = false;
        }
    }

    private void refresh() {
//                执行下载数据
        new getDataFromNet().execute(NewsUrl.getSchoolNewsUrl(1));

    }

    //加载更多
    @Override
    public void LoadMore() {
        currentPage++;
        isRefresh = false;
        new getDataFromNet().execute(NewsUrl.getSchoolNewsUrl(currentPage));
    }

    //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^处理数据加载^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    public class getDataFromNet extends AsyncTask<String, List<News>, List<News>> {
        @Override
        protected List<News> doInBackground(String... params) {
            List<News> allNews = NewsUrlPaster.getAllNews(params[0]);
            return allNews;
        }

        @Override
        protected void onPostExecute(List<News> newses) {
            listView.setLoadComplete();

//            设置加载动画消失
            waveSwipeRefreshLayout.setRefreshing(false);
            loadingView.setVisibility(View.GONE);
            if (newses == null && newsData == null) {
                failed_view.setVisibility(View.VISIBLE);

                return;
            }

            if (null == newsData || isRefresh) {
//                Toast.makeText(getActivity(), "刷新数据成功", Toast.LENGTH_SHORT).show();

            } else {

            }
            newsData = newses;
            //            缓存数据到本地
            Gson gson = new Gson();
            String newsJson = gson.toJson(newsData);
            SPUtils.put(getActivity(), Constant.SCHOOL_NEWS_DATA, newsJson);
            //设置更新daapter
            setAdapter(newsData);


            super.onPostExecute(newses);
        }
    }

    //对adapter进行操作
    private void setAdapter(final List<News> newses) {
        if (schoolNewsAdapter == null) {
            schoolNewsAdapter = new SchoolAdapter(getActivity(), newses);
            listView.setAdapter(schoolNewsAdapter);
        } else {
            if (isRefresh) {
                schoolNewsAdapter.replaceAll(newses);
            } else {
                schoolNewsAdapter.addAll(newses);
            }
        }
        listView.setOnItemClickListener(DepartmentItemClickLicener);
    }

    @Override
    public void onPause() {
        loadingView.setVisibility(View.GONE);
        super.onPause();
        MobclickAgent.onPageEnd("学校新闻");
    }

    AdapterView.OnItemClickListener DepartmentItemClickLicener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {


            Intent intent = new Intent();
            Object item = schoolNewsAdapter.getItem(position - 1);
            News news = (News) item;
            intent.setClass(getActivity(), NewsDetialActivity.class);
            intent.putExtra(Constant.SCHOOL_NEWS_TITLE, news.getTitle());
            intent.putExtra(Constant.SCHOOL_NEWS_URL, news.getUrl());
            intent.putExtra(Constant.DEPARTMENT_NAME, "SchoolNewFragment");
            startActivity(intent);

        }
    };

    /*
 * 对象转 json
 * obj 对象
 * */
    public String toJson(Object obj) {

        Gson gson = new Gson();
        return gson.toJson(obj);
    }

    /*
    * json转对象
    * classOfT 对象类型
    * */
    public <T> T toObj(String json, Type typeOfT) {
        Gson gson = new Gson();
        T t = gson.fromJson(json, typeOfT);
        return t;
    }
}
